package com.sitecsys.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sitecsys.config.Result;
import com.sitecsys.mapper.TbUserMapper;
import com.sitecsys.pojo.TbUser;
import com.sitecsys.service.TbUserService;
import com.sitecsys.utils.DefaultAvatarUtil;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sitecsys.utils.JwtUtils ;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LHB
 * @since 2024-01-06
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public Result login(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String password = jsonObj.getString("password");
        Map<String, String> map = new HashMap<>();
        TbUser user = tbUserMapper.login(phone, password);
        if (user == null) {
            return Result.error(201,"用户名或密码错误");
        }
        map.put("phone", String.valueOf(user.getPhone()));
        map.put("password", user.getPassword());
        String usertoken = JwtUtils.genereteToken(map);
        JSONObject data = new JSONObject();
        data.put("token", usertoken);
        return Result.success("登录成功",data);
    }

@Override
public Result register(JSONObject jsonObj) {
    // 验证必填字段不为空
    if (StringUtils.hasText(jsonObj.getString("phone")) && StringUtils.hasText(jsonObj.getString("password")) &&
            jsonObj.getJSONArray("security") != null && jsonObj.getJSONArray("security").size() == 3) {


        TbUser user = new TbUser();
        String username = jsonObj.getString("username");

        // 检查用户名是否已存在
        TbUser existedUser = tbUserMapper.selectByUsername(username);
        if (existedUser != null) {
            return Result.error("该用户名已被注册，请选择其他用户名");
        }

        user.setUsername(username);
        user.setPhone(jsonObj.getString("phone"));
        user.setPassword(jsonObj.getString("password"));
        user.setIsmanager(0);

        String userAvatarBytes;
        // 检查avatar字段是否存在并转换为字节数组
        String avatarStr = jsonObj.getString("avatar");
        if (StringUtils.hasText(avatarStr)) {
            try {
                user.setAvatar(avatarStr);
            } catch (Exception e) {
                log.error("将avatar字符串转换为字节失败", e);
                return Result.error("设置头像失败");
            }
        }else{
            //若无上传头像图片，则从本地上传一张图片作为默认头像
//            userAvatarBytes = DefaultAvatarUtil.getDefaultAvatarBytes();
//            user.setAvatar(userAvatarBytes);
        }

        String Facebase = jsonObj.getString("faceBase");
//        user.setFacebase(jsonObj.getString("facebase"));
        if (StringUtils.hasText(Facebase)) {
            try {
                user.setFacebase(Facebase);
            } catch (Exception e) {
                log.error("将avatar字符串转换为字节失败", e);
                return Result.error("设置人脸失败");
            }
        }
        JSONArray securityArray = jsonObj.getJSONArray("security");
        JSONObject o1 = securityArray.getJSONObject(0);
        JSONObject o2 = securityArray.getJSONObject(1);
        JSONObject o3 = securityArray.getJSONObject(2);

        user.setSecurityQ1(o1.getString("question1"));
        user.setSecurityQ2(o2.getString("question2"));
        user.setSecurityQ3(o3.getString("question3"));
        user.setSecurityA1(o1.getString("answer1"));
        user.setSecurityA2(o2.getString("answer2"));
        user.setSecurityA3(o3.getString("answer3"));


        // 执行插入操作
        try {
            if (tbUserMapper.insert(user) > 0) {
                return Result.success("注册成功");
            } else {
                return Result.error("用户注册失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("用户注册时发生错误", e);
            return Result.error("服务器内部错误，请联系管理员");
        }
    }
    return Result.error("缺少必要的注册信息");
}



    public Result getUserByPhone(HttpServletRequest request) {
        String token = request.getHeader("access-token");

        if (token == null) {
            return Result.error(1101,"Token not found");
        }

        try {

            DecodedJWT jwt = JwtUtils.getTokenInfo(token);
            String phone = jwt.getClaim("phone").asString();

            if (phone != null) {
                // 假设有一个UserService用于根据电话号码查询用户
                TbUser user = tbUserMapper.selectByPhone(phone);

                if (user != null) {
                    return Result.success("查询成功", user);
                } else {
                    return Result.error(1013,"User not found");
                }
            } else {
                return Result.error(1011,"Token payload doesn't contain phone information");
            }
        } catch (ExpiredJwtException e) {
            return Result.error(1012,"Token expired");
        } catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            return Result.error(1012,"Invalid token");
        }
        catch (Exception e) {
            return Result.error(1014,"System error");
        }
    }

    @Override
    public Result getUserByPhoneAndName(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String username = jsonObj.getString("username");
        TbUser user = tbUserMapper.selectByPhoneAndName(phone, username);
        if (user!= null) {
            return Result.success("查询成功",user);
        }
        return Result.error(1015,"该帐户不存在");
    }

    @Override
    public Result CheckUserByPhone(JSONObject jsonObj) {
        String username = jsonObj.getString("username");
        String A1 = jsonObj.getString("securityA1");
        String A2 = jsonObj.getString("securityA2");
        String A3 = jsonObj.getString("securityA3");
        TbUser user = tbUserMapper.selectByUsername(username);
        if ((A1.equals(user.getSecurityA1())) && (A2.equals(user.getSecurityA2())) && (A3.equals(user.getSecurityA3()))){
            return Result.success("密保问题通过！",200);
        }
        return Result.error(1016,"密保问题回答错误");
    }


    public Result updatePassword(JSONObject jsonObj) {

        String phone = jsonObj.getString("phone");
        String newPwd = jsonObj.getString("newPwd");
        TbUser user = tbUserMapper.selectByPhone(phone);
        if (user.getPassword().equals(newPwd)) {
            return Result.error("新密码不能与原密码相同");

        } else {
            user.setPassword(newPwd);
            tbUserMapper.updateById(user);
            return Result.success("修改成功");
        }

    }

//    public Result CheckUserByImage(JSONObject jsonObj) {
//        String imageBase = jsonObj.getString("imageBase");
//
//    }


}
